#import "AlipushFlutterPlugin.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import <UserNotifications/UserNotifications.h>

//控制台是否输出日志
static BOOL LogEnable = NO;

static BOOL PushOnActive = NO;

#define DLog(format,...)  if(LogEnable) {\
NSLog((@"| AliPUSH | Flutter | iOS |  %s[%d]" format), __FUNCTION__, __LINE__, ##__VA_ARGS__);\
}

@implementation AlipushFlutterPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"alipush"
            binaryMessenger:[registrar messenger]];
  AlipushFlutterPlugin* instance = [[AlipushFlutterPlugin alloc] init];
  instance.channel = channel;
  [registrar addApplicationDelegate:instance];
  [registrar addMethodCallDelegate:instance channel:channel];
}

//响应flutter
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
   DLog(@"handleMethodCall:%@",call.method);
  if ([@"setup" isEqualToString:call.method]) {
     [self setup:call result: result];
  } else if([@"setAlias" isEqualToString:call.method]) {
     [self setAlias:call result:result];
  } else if([@"deleteAlias" isEqualToString:call.method]) {
      [self deleteAlias:call result:result];
  } else if([@"setBadge" isEqualToString:call.method]) {
      [self setBadge:call result:result];
  } else if([@"setPushOnActive" isEqualToString:call.method]) {
      [self setPushOnActive:call result:result];
  } else if([@"setLogEnable" isEqualToString:call.method]) {
      [self setLogEnable:call result:result];
  } else {
    result(FlutterMethodNotImplemented);
  }
}


//初始化阿里云推送SDK
- (void)setup:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *arguments = call.arguments;
    // SDK初始化
    [CloudPushSDK asyncInit:arguments[@"appKey"] appSecret:arguments[@"appSecret"] callback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            DLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]);
        } else {
            DLog(@"Push SDK init failed, error: %@", res.error);
        }
    }];
}

//设置别名
- (void)setAlias:(FlutterMethodCall*)call result:(FlutterResult)result {
    DLog(@"setAlias:%@",call.arguments);
    NSString *alias = call.arguments;
    [CloudPushSDK addAlias:alias withCallback:^(CloudPushCallbackResult *res) {
        result([NSNumber numberWithInt:res.success]);
        if (res.success) {
            DLog(@"别名设置成功:%@",res.data);
        } else {
            DLog(@"别名设置失败:%@",[res.error localizedDescription]);
        }
    }];
}

//删除别名
- (void)deleteAlias:(FlutterMethodCall*)call result:(FlutterResult)result {
    DLog(@"deleteAlias:%@",call.arguments);
    NSString *alias = call.arguments;
    [CloudPushSDK removeAlias:alias withCallback:^(CloudPushCallbackResult *res) {
        result([NSNumber numberWithInt:res.success]);
        if (res.success) {
            DLog(@"别名删除成功:%@",res.data);
        } else {
            DLog(@"别名删除失败:%@",[res.error localizedDescription]);
        }
    }];
}

//设置小红点
- (void)setBadge:(FlutterMethodCall*)call result:(FlutterResult)result {
    DLog(@"setBadge:%@",call.arguments);
    NSInteger badge = [call.arguments[@"badge"] integerValue];
    if (badge < 0) {
        badge = 0;
    }
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: badge];
    [CloudPushSDK syncBadgeNum:badge withCallback:^(CloudPushCallbackResult *res) {}];
}

//当应用处于前台时收到推送，是否显示推送弹窗，默认否
- (void)setPushOnActive:(FlutterMethodCall*)call result:(FlutterResult)result {
    DLog(@"setPushOnActive:%@",call.arguments);
    NSInteger active = [call.arguments[@"active"] integerValue];
    PushOnActive = active;
}

//是否输出日志
- (void)setLogEnable:(FlutterMethodCall*)call result:(FlutterResult)result {
    BOOL enable = call.arguments;
    LogEnable = enable;
    DLog(@"开启日志输出");
}

//注册APNS
- (void)registerAPNS:(UIApplication *)application {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
    }
    else {
        // iOS < 8 Notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
}
#pragma mark - AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    DLog(@"iOS应用启动");
    
    //重置远端及本地角标
    application.applicationIconBadgeNumber = 0;
    [CloudPushSDK syncBadgeNum:0 withCallback:^(CloudPushCallbackResult *res) {}];
    
    [self registerAPNS:application];

    //iOS10设置代理，iOS以下直接获取推送信息
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        if(launchOptions) {
            NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
            [CloudPushSDK sendNotificationAck:userInfo];
            [_channel invokeMethod:@"onOpenNotification" arguments:userInfo];
        }
    }

    return YES;
}

/*
 *  推送注册成功回调，将返回的deviceToken上传到CloudPush服务器
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            DLog(@"Register deviceToken success.");
        } else {
            DLog(@"Register deviceToken failed, error: %@", res.error);
        }
    }];
}
/*
 *  推送注册失败回调
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"didFailToRegisterForRemoteNotificationsWithError %@", error);
}

//App处于打开状态时，点击打开通知
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
    DLog(@"Receive one notification.");
    // 取得APNS通知内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    // 内容
    NSString *content = [aps valueForKey:@"alert"];
    // badge数量
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
    // 播放声音
    NSString *sound = [aps valueForKey:@"sound"];
    // 取得Extras字段内容
    NSString *Extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段，key是自己定义的
    DLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]", content, (long)badge, sound, Extras);
    // iOS badge 清0
    application.applicationIconBadgeNumber = 0;
    // 通知打开回执上报
    // [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
    [CloudPushSDK sendNotificationAck:userInfo];
    [_channel invokeMethod:@"onReceiveNotification" arguments:userInfo];
}


//iOS10+处于前台收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    DLog(@"Receive a notification in foregound.");
    [_channel invokeMethod:@"onReceiveNotification" arguments: [self handleiOS10Notification:notification]];
    if (PushOnActive) {
        completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    } else {
        completionHandler(UNNotificationPresentationOptionNone);
    }
}


//iOS10+点击通知栏等操作进入收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSString *userAction = response.actionIdentifier;
    // 点击通知打开
    if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) {
        DLog(@"User opened the notification.");
        [_channel invokeMethod:@"onOpenNotification" arguments: [self handleiOS10Notification:response.notification]];
    }
    completionHandler();
}

/**
 *  处理iOS 10通知(iOS 10+)
 */
- (NSDictionary *)handleiOS10Notification:(UNNotification *)notification  API_AVAILABLE(ios(10.0)){
    UNNotificationRequest *request = notification.request;
    UNNotificationContent *content = request.content;
    NSDictionary *userInfo = content.userInfo;
    // 通知时间
    NSDate *noticeDate = notification.date;
    // 标题
    NSString *title = content.title;
    // 副标题
    NSString *subtitle = content.subtitle;
    // 内容
    NSString *body = content.body;
    // 角标
    int badge = [content.badge intValue];
    // 取得通知自定义字段内容，例：获取key为"Extras"的内容
    NSString *extras = [userInfo valueForKey:@"Extras"];
    // 通知打开回执上报
    [CloudPushSDK sendNotificationAck:userInfo];

    DLog(@"Notification, date: %@, title: %@, subtitle: %@, body: %@, badge: %d, extras: %@.", noticeDate, title, subtitle, body, badge, extras);
    return userInfo;
}




@end
